//
//  DataManager.m
//  HaiTongHop
//
//  Created by Nguyen Cong Huy on 12/18/14.
//  Copyright (c) 2014 Nguyen Cong Huy. All rights reserved.
//

#import "DataManager.h"
#import "SourceEntity.h"

#define kSourceKey @"kSourceKey"
#define kLastTimeUpdateServerKey @"kLastTimeUpdateServerKey"
#define kInvalidVersion (-1)
#define kDurationBetweenUpdateServer (6*3600)

@interface DataManager() {
    NSOperationQueue* downloadOperationQueue;
}

@end

@implementation DataManager

SYNTHESIZE_SINGLETON_FOR_CLASS(DataManager, sharedDataManager)

- (instancetype)init {
    if(self = [super init]) {
        self.currentSourceVersion = kInvalidVersion;
        self.sourcesArray = [[NSMutableArray alloc] init];
        
        downloadOperationQueue = [[NSOperationQueue alloc] init];
    }
    return self;
}

- (void)loadRemoteSourceWithComplete:(void (^)(BOOL isNewData))complete {
    NSString* jsonString = [[NSUserDefaults standardUserDefaults] objectForKey:kSourceKey];
    
    if(jsonString == nil) {
        NSError* error = nil;
        NSString* filePath = [[NSBundle mainBundle] pathForResource:@"hai" ofType:@"json"];
        jsonString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
        
        if(error) {
            NSLog(@"Error read local file: %@", error);
            return;
        }
    }
    
    [self parseRemoteSourceJsonString:jsonString complete:complete];
    
    // update from server
    NSTimeInterval lastTimeUpdateServer = 0;
    NSNumber* lastTimeUpdateServerNumber = [[NSUserDefaults standardUserDefaults] objectForKey:kLastTimeUpdateServerKey];
    if(lastTimeUpdateServerNumber && [lastTimeUpdateServerNumber isKindOfClass:[NSNumber class]]) {
        lastTimeUpdateServer = [lastTimeUpdateServerNumber doubleValue];
    }
    
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
    NSTimeInterval durationFromLastUpdate = currentTime - lastTimeUpdateServer;
    if(durationFromLastUpdate > kDurationBetweenUpdateServer) {
        [self loadFromServerWithComplete:complete];
        [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithDouble:currentTime] forKey:kLastTimeUpdateServerKey];
    }
}

- (void)loadFromServerWithComplete:(void (^)(BOOL isNewData))complete{
    NSString* urlString = @"https://dl.dropboxusercontent.com/u/30471473/Server/Hai/hai.json";
    NSMutableURLRequest* urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    
    AFHTTPRequestOperation* operation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
    operation.responseSerializer = [AFHTTPResponseSerializer serializer];
    operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString* htmlResult = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//        NSLog(@"Html result: %@", htmlResult);
        
        [self parseRemoteSourceJsonString:htmlResult complete:complete];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Fail load from server: %@", error);
    }];
    [downloadOperationQueue addOperation:operation];
}

- (void)parseRemoteSourceJsonString:(NSString*)jsonString complete:(void (^)(BOOL isNewData))complete {
    
    NSError *error;
    NSDictionary* jsonDictionary = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];
    
    if(error) {
        NSLog(@"Error convert json string to dictionary: %@", error);
        return;
    }
    
    int version = -1;
    NSString* versionString = [jsonDictionary objectForKey:@"version"];
    if(versionString && [versionString isKindOfClass:[NSString class]]) {
        version = [versionString intValue];
    }
    
    if(version > self.currentSourceVersion) {
        if(self.currentSourceVersion != kInvalidVersion) {
            [[NSUserDefaults standardUserDefaults] setObject:jsonString forKey:kSourceKey];
        }
        self.currentSourceVersion = version;
    }
    else {
        if(complete) {
            complete(NO);
        }
        return;
    }
    
    NSArray* pageArray = [jsonDictionary objectForKey:@"pages"];
    [self.sourcesArray removeAllObjects];
    
    if(pageArray && [pageArray isKindOfClass:[NSArray class]]) {
        
        for (NSDictionary* pageDictionary in pageArray) {
            
            if([pageDictionary isKindOfClass:[NSDictionary class]]) {
                SourceEntity* sourceEntity = [[SourceEntity alloc] init];
                sourceEntity.iconString = [pageDictionary objectForKey:@"icon"];
                sourceEntity.linkDictionary = [pageDictionary objectForKey:@"links"];
                sourceEntity.title = [pageDictionary objectForKey:@"title"];
                
                [self.sourcesArray addObject:sourceEntity];
            }
        }
    }
    
    if(complete) {
        complete(YES);
    }
}

@end
